from khronos.utils.files import find_files, re_filter
from khronos.utils import Logger, Prompt
import shutil

src_zip_filter = re_filter(r"\d+\.\d+\.\d+\w*_\d{8}\.zip$")
_log = Logger()
_prompt = Prompt("Proceed?")

def archive(directory, archive_dir, recursive=True, verbose=True):
    """This function moves source zips created by the bundle utility into the archive directory 
    (specified as a global variable in this file). Basically it just serves to keep the source 
    directories neat and clean of zip files."""
    _log.set_enabled(verbose)
    filematches = find_files(directory, [src_zip_filter], recursive)
    if len(filematches) == 0:
        _log.warn("No file matches found.")
        return
    for filepath in filematches:
        _log(filepath, indent=1)
    _log.info("Moving source archives to %s" % (archive_dir,))
    answer = _prompt()
    if answer not in ("y", "yes"):
        return
    for filepath in filematches:
        _log("Moving %s ..." % (filepath,), indent=1, newline=False)
        try:
            shutil.move(filepath, archive_dir)
        except Exception, exc:
            _log(" failed")
            _log.error("%s: %s" % (exc.__class__.__name__, exc))
        else:
            _log(" ok")
    _log.info("Archive operation finished.")
    
if __name__ == "__main__":
    from optparse import OptionParser
    import sys
    
    parser = OptionParser(description="Utility for moving Python source code zip archives to "
                          "a specified archive directory", 
                          usage="%prog [options]", version="%prog 0.0.1a")
    parser.add_option("-a", "--archive", dest="archive", type="string", default=".", 
                      help="specify the archive directory (default is current directory)")
    parser.add_option("-d", "--directory", dest="directory", type="string", default=".", 
                      help="specify the target directory (default is current directory)")
    parser.add_option("-q", "--quiet", dest="verbose", action="store_false", default=True, 
                      help="do not print information messages")
    parser.add_option("-r", "--recursive", dest="recursive", action="store_true", default=False, 
                      help="recursively check for source archives")
    
    options, args = parser.parse_args(sys.argv)
    archive(options.directory, options.archive, options.recursive, options.verbose)
    sys.exit(0)
    
